package org.example.manage;

import org.example.User;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ESOptiation {

    @Resource
    public ElasticsearchRestTemplate elasticsearchRestTemplate;
    public void createIndex(){
        // 指定文档的数据实体类
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(User.class);
        // 创建索引
        boolean b = indexOperations.create();
        System.out.println(b);
    }

    public void insertIndex(User user){
        // 指定文档的数据实体类
        User save = elasticsearchRestTemplate.save(user);
        if(save != null){
            System.out.println("创建成功");
        }else{
            System.out.println("创建失败");
        }
    }

    public List<User> searchIndex(){
        // 指定文档的数据实体类
        Query all = Query.findAll();
        SearchHits<User> search = elasticsearchRestTemplate.search(all, User.class);
        List<SearchHit<User>> searchHits = search.getSearchHits();
        List<User> users = new ArrayList<>();
        for (SearchHit<User> searchHit : searchHits) {
            User user = searchHit.getContent();
            users.add(user);
        }
        return users;


    }
}
